<template>
    <div class="min-h-screen bg-gradient-to-br from-purple-50 to-blue-50 py-12 px-4 sm:px-6 lg:px-8">
        <!-- 主卡片容器 -->
        <div
            class="max-w-4xl mx-auto bg-white rounded-2xl shadow-2xl overflow-hidden transition-all duration-300 hover:shadow-3xl">
            <!-- 头部区域 -->
            <div class="bg-gradient-to-r from-purple-600 to-blue-500 px-8 py-6">
                <h1 class="text-3xl font-bold text-white text-center tracking-wide">
                    <i class="fas fa-sync-alt mr-3 transform transition hover:rotate-180"></i>
                    视频循环魔法工坊
                </h1>
            </div>

            <!-- 主体内容 -->
            <div class="px-8 py-10 space-y-8">
                <!-- 上传区域 -->
                <div class="space-y-4">
                    <label class="block text-lg font-semibold text-gray-700 mb-4">
                        <i class="fas fa-upload mr-2 text-purple-600"></i>
                        上传你的创意视频
                    </label>

                    <!-- 拖拽上传区 -->
                    <div @dragover.prevent="isDragging = true" @dragleave.prevent="isDragging = false"
                        @drop.prevent="handleDrop"
                        class="border-2 border-dashed border-gray-300 rounded-xl p-8 text-center transition-all duration-200 cursor-pointer"
                        :class="isDragging ? 'border-purple-500 bg-purple-50' : 'border-gray-200 hover:border-purple-300'">
                        <div class="max-w-md mx-auto flex flex-col items-center">
                            <div
                                class="w-16 h-16 bg-purple-100 rounded-full flex items-center justify-center mb-4 transition-transform hover:scale-110">
                                <img src="@/assets/upload.svg" class="w-8 h-8 text-purple-600" />
                            </div>
                            <p class="text-gray-600 mb-2">拖放视频文件到此区域</p>
                            <p class="text-sm text-gray-500">支持MP4, MOV, AVI等格式</p>
                            <input type="file" ref="videoInput" accept="video/*" @change="handleFileChange"
                                class="hidden">
                        </div>
                    </div>
                </div>

                <!-- 视频信息展示 -->
                <div v-if="videoInfo" class="bg-gray-50 rounded-lg p-6 shadow-inner space-y-6">
                    <!-- 原有的视频信息显示 -->
                    <div class="grid grid-cols-2 md:grid-cols-3 gap-4 text-sm">
                        <div class="space-y-1">
                            <label class="text-gray-500">文件名称</label>
                            <p class="font-medium truncate">{{ videoInfo.name }}</p>
                        </div>
                        <div class="space-y-1">
                            <label class="text-gray-500">视频尺寸</label>
                            <p class="font-medium">{{ videoInfo.dimensions }}</p>
                        </div>
                        <div class="space-y-1">
                            <label class="text-gray-500">文件大小</label>
                            <p class="font-medium">{{ videoInfo.size }}</p>
                        </div>
                    </div>

                    <!-- 添加原始视频预览 -->
                    <div class="border rounded-lg overflow-hidden">
                        <div class="bg-gray-800 p-3">
                            <h3 class="text-white font-medium text-sm flex items-center">
                                <i class="fas fa-file-video mr-2 text-purple-400"></i>
                                原始视频预览
                            </h3>
                        </div>
                        <video 
                            ref="previewVideo" 
                            :src="previewUrl" 
                            controls 
                            class="w-full aspect-video bg-gray-900">
                        </video>
                    </div>
                </div>

                <!-- 控制面板 -->
                <div class="grid grid-cols-2 gap-6">
                    <button @click="handleReverseVideo"
                        class="transform transition hover:-translate-y-1 h-14 bg-gradient-to-r from-purple-500 to-blue-500 hover:to-purple-600 text-white rounded-xl font-semibold shadow-lg flex items-center justify-center space-x-3">
                        <i class="fas fa-retweet"></i>
                        <span>生成反转视频</span>
                    </button>

                    <button @click="handleProcessVideo"
                        class="transform transition hover:-translate-y-1 h-14 bg-gradient-to-r from-green-400 to-emerald-500 hover:to-green-600 text-white rounded-xl font-semibold shadow-lg flex items-center justify-center space-x-3">
                        <i class="fas fa-infinity"></i>
                        <span>生成循环视频</span>
                    </button>
                </div>

                <!-- 进度指示 -->
                <div v-if="showProgress" class="space-y-4">
                    <div class="flex items-center justify-between text-sm">
                        <span class="text-gray-600 font-medium">处理进度</span>
                        <span class="text-purple-600 font-bold">{{ progressPercent }}%</span>
                    </div>
                    <div class="h-3 bg-gray-200 rounded-full overflow-hidden">
                        <div class="h-full bg-gradient-to-r from-purple-400 to-blue-400 transition-all duration-500 ease-out"
                            :style="{ width: progressPercent + '%' }"></div>
                    </div>
                </div>

                <div id="status" class="text-center text-sm text-gray-500">{{ statusMessage }}</div>

                <!-- 视频预览 -->
                <div v-if="showVideo" class="border rounded-xl overflow-hidden shadow-lg">
                    <div class="bg-gray-800 p-3">
                        <h3 class="text-white font-medium text-sm flex items-center">
                            <i class="fas fa-play-circle mr-2 text-green-400"></i>
                            预览你的创意作品
                        </h3>
                    </div>
                    <video v-if="videoUrl" ref="outputVideo" :src="videoUrl" controls
                        class="w-full aspect-video bg-gray-900"></video>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { createFFmpeg, fetchFile } from '@ffmpeg/ffmpeg';

export default {
    name: 'VideoLoopMaker',
    data() {
        return {
            ffmpeg: null,
            isFFmpegLoaded: false,
            statusMessage: '',
            progressPercent: 0,
            showProgress: false,
            showVideo: false,
            videoUrl: null,
            isDragging: false,
            videoInfo: null,
            currentFile: null  // 添加当前文件存储
        };
    },
    async mounted() {
        this.ffmpeg = createFFmpeg({
            log: true,
            progress: ({ ratio }) => {
                this.progressPercent = Math.round(ratio * 100);
            }
        });

        this.loadFFmpeg();
    },
    methods: {
        // 提取视频处理逻辑为单独的方法
        async handleProcessVideo() {
            const file = this.currentFile
            if (!file) {
                this.statusMessage = '请先选择视频文件';
                return;
            }
            try {
                this.statusMessage = '正在处理视频...';
                this.showProgress = true;
                this.showVideo = false;

                // 获取并显示视频信息
                await this.extractVideoInfo(file);

                // Write the input file to FFmpeg's virtual filesystem
                this.ffmpeg.FS('writeFile', 'input.mp4', await fetchFile(file));

                // First, create the reversed version
                await this.ffmpeg.run(
                    '-i', 'input.mp4',
                    '-vf', 'reverse',
                    '-af', 'areverse',
                    'reversed.mp4'
                );

                // Create a file list for concatenation
                const fileContent = 'file input.mp4\nfile reversed.mp4';
                this.ffmpeg.FS('writeFile', 'list.txt', new TextEncoder().encode(fileContent));

                // Concatenate the original and reversed videos
                await this.ffmpeg.run(
                    '-f', 'concat',
                    '-safe', '0',
                    '-i', 'list.txt',
                    '-c', 'copy',
                    'output.mp4'
                );

                // Read the output file
                const data = this.ffmpeg.FS('readFile', 'output.mp4');

                // Create a URL for the output video
                if (this.videoUrl) {
                    URL.revokeObjectURL(this.videoUrl);
                }
                this.videoUrl = URL.createObjectURL(new Blob([data.buffer], { type: 'video/mp4' }));

                // Display the combined video
                this.showVideo = true;
                this.showProgress = false;
                this.statusMessage = '视频处理完成！正在播放正反循环视频。';

                // Clean up
                this.ffmpeg.FS('unlink', 'input.mp4');
                this.ffmpeg.FS('unlink', 'reversed.mp4');
                this.ffmpeg.FS('unlink', 'list.txt');
                this.ffmpeg.FS('unlink', 'output.mp4');
            } catch (error) {
                console.error(error);
                this.statusMessage = 'An error occurred while processing the video.';
                this.showProgress = false;
            }
        },

        // 添加提取视频信息的方法
        async extractVideoInfo(file) {
            // 基本文件信息
            const fileSize = this.formatFileSize(file.size);
            const format = file.type.split('/')[1].toUpperCase();

            // 创建临时视频元素获取更多信息
            const videoElement = document.createElement('video');
            videoElement.preload = 'metadata';

            // 创建临时URL
            const tempUrl = URL.createObjectURL(file);
            videoElement.src = tempUrl;

            // 等待元数据加载
            await new Promise((resolve) => {
                videoElement.onloadedmetadata = () => {
                    resolve();
                };
            });

            // 获取视频信息
            const width = videoElement.videoWidth;
            const height = videoElement.videoHeight;
            const duration = this.formatDuration(videoElement.duration);

            // 使用FFmpeg获取帧率信息
            let frameRate = '未知';
            try {
                this.ffmpeg.FS('writeFile', 'temp.mp4', await fetchFile(file));
                await this.ffmpeg.run('-i', 'temp.mp4');
                // 帧率信息通常会在FFmpeg的日志输出中，但这里简化处理
                frameRate = '自动检测';
                this.ffmpeg.FS('unlink', 'temp.mp4');
            } catch (e) {
                // FFmpeg在分析文件时会抛出错误，但仍然会输出信息
                frameRate = '自动检测';
            }

            // 释放临时URL
            URL.revokeObjectURL(tempUrl);

            // 设置视频信息
            this.videoInfo = {
                name: file.name,
                size: fileSize,
                dimensions: `${width} x ${height}`,
                duration: duration,
                frameRate: frameRate,
                format: format
            };
        },

        // 格式化时长
        formatDuration(seconds) {
            const min = Math.floor(seconds / 60);
            const sec = Math.floor(seconds % 60);
            return `${min}:${sec.toString().padStart(2, '0')}`;
        },

        // 格式化文件大小 (已有此方法，确保它可用)
        formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';

            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));

            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        },
        async loadFFmpeg() {
            if (!this.isFFmpegLoaded) {
                this.statusMessage = '正在加载 FFmpeg...';
                await this.ffmpeg.load();
                this.isFFmpegLoaded = true;
                this.statusMessage = 'FFmpeg 已就绪！';
            }
        },
        async handleFileChange(e) {
            const file = e.target.files?.item(0);
            if (!file) return;
            this.currentFile = file;
            // 创建预览URL
            if (this.previewUrl) {
                URL.revokeObjectURL(this.previewUrl);
            }
            this.previewUrl = URL.createObjectURL(file);
            await this.extractVideoInfo(file);
        },

        handleDrop(e) {
            this.isDragging = false;
            const file = e.dataTransfer?.files[0];
            if (file && file.type.startsWith('video/')) {
                this.currentFile = file;
                // 创建预览URL
                if (this.previewUrl) {
                    URL.revokeObjectURL(this.previewUrl);
                }
                this.previewUrl = URL.createObjectURL(file);
                this.extractVideoInfo(file);
            } else {
                this.statusMessage = '请上传视频文件';
            }
        },

        // 添加反转视频处理方法
        async handleReverseVideo() {
            if (!this.currentFile) {
                this.statusMessage = '请先选择视频文件';
                return;
            }
            try {
                this.statusMessage = '正在生成反转视频...';
                this.showProgress = true;
                this.showVideo = false;

                // 写入输入文件
                this.ffmpeg.FS('writeFile', 'input.mp4', await fetchFile(this.currentFile));

                // 生成反转视频
                await this.ffmpeg.run(
                    '-i', 'input.mp4',
                    '-vf', 'reverse',
                    '-af', 'areverse',
                    'output.mp4'
                );

                // 读取输出文件
                const data = this.ffmpeg.FS('readFile', 'output.mp4');

                // 创建视频URL
                if (this.videoUrl) {
                    URL.revokeObjectURL(this.videoUrl);
                }
                this.videoUrl = URL.createObjectURL(new Blob([data.buffer], { type: 'video/mp4' }));

                // 显示视频
                this.showVideo = true;
                this.showProgress = false;
                this.statusMessage = '反转视频生成完成！';

                // 清理文件系统
                this.ffmpeg.FS('unlink', 'input.mp4');
                this.ffmpeg.FS('unlink', 'output.mp4');
            } catch (error) {
                console.error(error);
                this.statusMessage = '生成反转视频时发生错误';
                this.showProgress = false;
            }
        },

        // ... 其他方法保持不变 ...
    },
    beforeUnmount() {
        // Clean up resources
        if (this.videoUrl) {
            URL.revokeObjectURL(this.videoUrl);
        }
        if (this.previewUrl) {
            URL.revokeObjectURL(this.previewUrl);
        }
    }
}
</script>

<style>
/* 可以添加一些自定义样式 */
.border-dashed {
    border-style: dashed;
}
</style>